package SeedBank

import org.springframework.dao.DataIntegrityViolationException

/**
 * Handles the seed features and tell the app what to do when an action is
 * performed for a particular seed
 * 
 * @author Nathan
 *
 */

class SeedController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	
	/**
	 * searches the results
	 * @return the list of found objects
	 */
	def searchResults(){}
	
	/**
	 * searches the listings
	 * @return the list of found objects
	 */
	def search(){}
	
	/**
	 * tells the app what to do when a purchase is initiated on a seed
	 * @return void
	 */
	def purchase(){
		def purchasedSeed = Seed.get(params.id)
		
		if(session.user){
			if(!purchasedSeed?.user?.id.equals(session?.user?.id)){
				def purchase = new Purchase(scientificName: purchasedSeed.scientificName,
					quantity: purchasedSeed.quantity,
					price: purchasedSeed.price,
					user:session.user,
					endOfGrowingSeason: purchasedSeed.endOfGrowingSeason,
					startOfGrowingSeason: purchasedSeed.startOfGrowingSeason,
					harvestingInformation: purchasedSeed.harvestingInformation,
					specialRequirements: purchasedSeed.specialRequirements,
					hardinessZone: purchasedSeed.hardinessZone,
					commonName: purchasedSeed.commonName)
				
					purchase.save()
					flash.message = "Order successfully created!"
					purchasedSeed.delete()
					redirect(action:"list")
			}else{
				flash.message = "Can't buy your own seed!"
				redirect(action:"list")
			}
			
		}else{
			flash.message = "Must be logged in to buy seeds!"
			redirect(action:"list")
		}		
	}
	
	/**
	 * Performs search by hardiness or scientific name
	 * @return void
	 */
	def lookUp(){
		
		def seeds
	
		if(params.searchBy==null || params.searchFor==null){
			flash.message = "Invalid search!"
			redirect(action:"search")
		}
		else{
			if(params.searchBy.equals("Hardiness Zone") && params.searchFor.isInteger()){
				seeds = Seed.findAllByHardinessZone(params.int('searchFor'))
				if(seeds.size() == 0)
					flash.message = "No results found!"
				flash.message = seeds.size() + " result(s) found!"
				render(view:'SearchResults', model: [seeds:seeds])
			}else if(params.searchBy.equals("Scientific Name")){
				seeds = Seed.findAllByScientificName(params.searchFor)
				if(seeds.size() == 0)
					flash.message = "No result(s) found!"
				flash.message = seeds.size() + " results found!"	
				render(view:'SearchResults', model: [seeds:seeds])
			}else{
				flash.message = "Invalid search!"
				redirect(action:"search")
			}
		}
		
	}
	
	/**
	 * the index in the list
	 * @return the index
	 */
    def index() {
        redirect(action: "list", params: params)
    }
	
	/**
	 * creates the seed listings
	 * @return the list
	 */
	def list() {

		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		[seedInstanceList: Seed.list(params), seedInstanceTotal: Seed.count()]
		
	}

	/**
	 * creates seed instances
	 * @return the seed
	 */
    def create() {
		if(!session.user){
			flash.message = "Login before creating a seed!"
			redirect(controller: "User", action: "login")
		}else{
			[seedInstance: new Seed(params)]
		}
        
    }
	
	/**
	 * saves the seed instance's information
	 * @return void
	 */
    def save() {
        def seedInstance = new Seed(params)
        if (!seedInstance.save(flush: true)) {
            render(view: "create", model: [seedInstance: seedInstance])
            return
        }

		flash.message = message(code: 'default.created.message', args: [message(code: 'seed.label', default: 'Seed'), seedInstance.id])
        redirect(action: "show", id: seedInstance.id)
    }
	
	/**
	 * displays the seed instance's information
	 * @return void
	 */
    def show() {
        def seedInstance = Seed.get(params.id)
        if (!seedInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'seed.label', default: 'Seed'), params.id])
            redirect(action: "list")
            return
        }

        [seedInstance: seedInstance]
    }
	
	/**
	 * edits the seed instance's information
	 * @return void
	 */
    def edit() {
		
        def seedInstance = Seed.get(params.id)
		
		if(seedInstance.user.id.equals(session.user?.id)){
			
			if (!seedInstance) {
				flash.message = message(code: 'default.not.found.message', args: [message(code: 'seed.label', default: 'Seed'), params.id])
				redirect(action: "list")
				return
			}
	
			[seedInstance: seedInstance]
		}else{
			flash.message = "Not your seed, cant do that!"
			redirect(action: "show", id: params.id)
		}
        
    }
	
	/**
	 * updates the seed instance's information
	 * @return void
	 */
    def update() {
        def seedInstance = Seed.get(params.id)
        if (!seedInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'seed.label', default: 'Seed'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (seedInstance.version > version) {
                seedInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'seed.label', default: 'Seed')] as Object[],
                          "Another user has updated this Seed while you were editing")
                render(view: "edit", model: [seedInstance: seedInstance])
                return
            }
        }

        seedInstance.properties = params

        if (!seedInstance.save(flush: true)) {
            render(view: "edit", model: [seedInstance: seedInstance])
            return
        }

		flash.message = message(code: 'default.updated.message', args: [message(code: 'seed.label', default: 'Seed'), seedInstance.id])
        redirect(action: "show", id: seedInstance.id)
    }
	
	/**
	 * deletes the seed instance
	 * @return void
	 */
    def delete() {
        def seedInstance = Seed.get(params.id)
		
		if(session.user?.id.equals(seedInstance.user.id)){
			if (!seedInstance) {
				flash.message = message(code: 'default.not.found.message', args: [message(code: 'seed.label', default: 'Seed'), params.id])
				redirect(action: "list")
				return
			}
	
			try {
				seedInstance.delete(flush: true)
				flash.message = message(code: 'default.deleted.message', args: [message(code: 'seed.label', default: 'Seed'), params.id])
				redirect(action: "list")
			}
			catch (DataIntegrityViolationException e) {
				flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'seed.label', default: 'Seed'), params.id])
				redirect(action: "show", id: params.id)
			}
		}else{
			flash.message = "Not your seed, cant do that!"
			redirect(action: "show", id: params.id)
		}
			
	
	}
        

}
